from . import role_blueprint
from flask import render_template, url_for, jsonify, request, abort
from ..models.tables import Menu, Role, RoleMenu
from .. import db
from ..utils.common import set_response, get_post_data
from ..config.config import CodeMap


@role_blueprint.route('/list')
def role_list():
    all_roles = Role.query.all()
    return render_template('role/role_list.html', role_list=all_roles)


@role_blueprint.route('/add')
def add_role():
    all_menu = Menu.query.filter_by(parent_id=0).all()
    return render_template('role/add_role.html', all_menu=all_menu)


@role_blueprint.route('/add.do', methods=['POST'])
def do_add_role():
    name = get_post_data('name')
    desc = get_post_data('desc')
    menus = get_post_data('menus')
    if name is None or desc is None or menus is None or len(menus) <= 0:
        return set_response(CodeMap.PARAMS_ERROR, CodeMap.PARAMS_ERROR_MSG, None)
    new_role = Role(name=name, desc=desc)
    db.session.add(new_role)
    db.session.commit()
    for i in menus:
        new_role_menu = RoleMenu(role_id=new_role.id, menu_id=int(i))
        db.session.add(new_role_menu)
    db.session.commit()
    return set_response(CodeMap.SUCCESS, CodeMap.SUCCESS_MSG, {'role': new_role.id})


@role_blueprint.route('/update')
def update_role():
    role_id = request.args.get('id')
    if role_id is None:
        return abort(404)
    role = Role.query.get(int(role_id))
    if role is None:
        return abort(404)
    role_menu = []
    for i in role.menus:
        role_menu.append(i.menu_id)
    all_menu = Menu.query.filter_by(parent_id=0).all()
    return render_template('role/update_role.html', role=role, role_menus=role_menu, all_menu=all_menu)


@role_blueprint.route('/update.do', methods=['POST'])
def do_update_role():
    role_id = get_post_data('id')
    name = get_post_data('name')
    desc = get_post_data('desc')
    menus = get_post_data('menus')
    if role_id is None or name is None or desc is None or menus is None or len(menus) <= 0:
        return set_response(CodeMap.PARAMS_ERROR, CodeMap.PARAMS_ERROR_MSG, None)
    role = Role.query.get(int(role_id))
    role.desc = desc
    role.name = name
    db.session.query(RoleMenu).filter(RoleMenu.role_id == role_id).delete()
    for i in menus:
        role_menu = RoleMenu(role_id=role_id, menu_id=i)
        db.session.add(role_menu)
    db.session.commit()
    return set_response(CodeMap.SUCCESS, CodeMap.SUCCESS_MSG, None)


@role_blueprint.route('/delete.do', methods=['POST'])
def delete_role():
    id = get_post_data('id')
    if id is None:
        return set_response(CodeMap.PARAMS_ERROR, CodeMap.PARAMS_ERROR_MSG, None)
    db.session.query(Role).filter(Role.id == id).delete()
    db.session.query(RoleMenu).filter(RoleMenu.role_id == id).delete()
    db.session.commit()
    return set_response(CodeMap.SUCCESS, CodeMap.SUCCESS_MSG, None)